package com.md24housecall.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.md24housecall.activity.R;
import com.md24housecall.net.UrlBuilder;
import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyLog;
import com.md24housecall.util.Utils;

public class LoginIHealthFragment extends Fragment{
	private View mainView;
	private WebView mWebView;
	private ProgressBar mProgressBar;
//	private OnLoginListener listener;
	protected TextView txvError;
	private ConnectivityChangeReceiver receiver=new ConnectivityChangeReceiver();
	private Handler mHandler=new Handler();
	private final int DELAY=5000;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view=inflater.inflate(R.layout.login_ihealth, container,false);
		mainView=view;
		try{
			initLayout();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return view;
	}
	
	private void checkAndRetry(boolean isDisconnect){
		if(!Utils.getInstance().isNetworkAvailable(getActivity()) || isDisconnect){
			txvError.setVisibility(View.VISIBLE);
			mProgressBar.setVisibility(View.GONE);
			mWebView.setVisibility(View.GONE);
			return;
		}else{
			txvError.setVisibility(View.GONE);
			mWebView.setVisibility(View.VISIBLE);
			mWebView.loadUrl(Uri.parse(UrlBuilder.URL_LOGIN_IHEALTH)+GlobalConstant.getInstance().code);
		}
	}
	
	@SuppressLint("SetJavaScriptEnabled")
	private void initLayout(){
		mProgressBar=(ProgressBar)mainView.findViewById(R.id.progressBar);
		getActivity().registerReceiver(receiver, new IntentFilter(
	            ConnectivityManager.CONNECTIVITY_ACTION));
		txvError=(TextView)mainView.findViewById(R.id.txvError);
		
		mWebView=(WebView)mainView.findViewById(R.id.webView);
		mWebView.getSettings().setJavaScriptEnabled(true);
		checkAndRetry(false);
		mWebView.setWebViewClient(new WebViewClient(){
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				super.onPageStarted(view, url, favicon);
				MyLog.d(GlobalConstant.TAG,"page start: "+url);
				mProgressBar.setVisibility(View.VISIBLE);
			}
			
			
			@Override
			public void onPageFinished(final WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				MyLog.d(GlobalConstant.TAG,"onPageFinished: "+url);
				mProgressBar.setVisibility(View.GONE);
				if(url.startsWith(UrlBuilder.REDIRECT_URL)){
					mProgressBar.setVisibility(View.VISIBLE);
					view.setVisibility(View.INVISIBLE);
					mHandler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							GlobalConstant.getInstance().isUpdateIhealthUser=true;
							getActivity().onBackPressed();
						}
					}, DELAY);
					
				}
			}
		});
	}
	
	public void setOnLoginListener(OnLoginListener listener){
//		this.listener=listener;
	}
	
	public interface OnLoginListener{
		public void onLoginComplete();
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(receiver!=null){
			getActivity().unregisterReceiver(receiver);
		}
	}
	
	public class ConnectivityChangeReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			checkConnection(intent, GlobalConstant.TAG);
		}
		
		private void checkConnection(Intent intent, String tag) {
//			Toast.makeText(getActivity(), intent.getAction(), Toast.LENGTH_LONG).show()	;
//		    MyLog.d(tag, "action: " + intent.getAction());
//		    MyLog.d(tag, "component: " + intent.getComponent());
		    Bundle extras = intent.getExtras();
		    boolean noConnection=false;
		    boolean isDisconnect=false;
		    if (extras != null) {
		       for (String key: extras.keySet()) {
		    	   MyLog.d(tag, "key [" + key + "]: " +extras.get(key));
		    	   if(extras.get(key).toString().contains("DISCONNECTED/DISCONNECTED"))
		    		   isDisconnect=true;
		    	   if(key.equals("noConnectivity"))
		    		   noConnection=true;
		       }
		       if(noConnection&& isDisconnect)
		    	   checkAndRetry(true);
		       else
		    	   checkAndRetry(false);
		    }
		    else {
		    	MyLog.d(tag, "no extras");
		    }
		 }
	}
}
